#include "operationdelegate.h"
#include <QApplication>
#include <QMouseEvent>
#include <QPainter>

OperationDelegate::OperationDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

void OperationDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
                              const QModelIndex &index) const
{
    QStyledItemDelegate::paint(painter, option, index);

    // 只在绘制第7列的按钮
    if (index.column() == 7) {
        painter->save();

        // 绘制上传按钮
        m_uploadRect = getButtonRect(option.rect, 0);
        //一个按钮的描述信息 但不是真的按钮
        QStyleOptionButton uploadButton;
        //按钮的位置 是一个QRect 矩形描述信息
        uploadButton.rect = m_uploadRect;
        //文本
        uploadButton.text = "上传";
        //启用按钮
        uploadButton.state = QStyle::State_Enabled;

        // 绘制删除按钮
        m_deleteRect = getButtonRect(option.rect, 1);
        QStyleOptionButton deleteButton;
        deleteButton.rect = m_deleteRect;
        deleteButton.text = "删除";
        deleteButton.state = QStyle::State_Enabled;

        // 绘制查看按钮
        m_viewRect = getButtonRect(option.rect, 2);
        QStyleOptionButton viewButton;
        viewButton.rect = m_viewRect;
        viewButton.text = "查看";
        viewButton.state = QStyle::State_Enabled;

        // 绘制按钮
        QApplication::style()->drawControl(QStyle::CE_PushButton, &uploadButton, painter);
        QApplication::style()->drawControl(QStyle::CE_PushButton, &deleteButton, painter);
        QApplication::style()->drawControl(QStyle::CE_PushButton, &viewButton, painter);

        painter->restore();
    }
}

QSize OperationDelegate::sizeHint(const QStyleOptionViewItem &option,
                                  const QModelIndex &index) const
{
    return QSize(200, 40); // 固定操作列的大小
}

bool OperationDelegate::editorEvent(QEvent *event, QAbstractItemModel *model,
                                    const QStyleOptionViewItem &option, const QModelIndex &index)
{
    //触发编辑时间调用 筛选我们关心的事件
    if (event->type() == QEvent::MouseButtonPress && index.column() == 7) {

        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        //获取鼠标点击坐标
        QPoint pos = mouseEvent->pos();
        //判断在那个按钮内
        if (m_uploadRect.contains(pos)) {
            emit uploadClicked(index.row());
            return true;
        } else if (m_deleteRect.contains(pos)) {
            emit deleteClicked(index.row());
            return true;
        } else if (m_viewRect.contains(pos)) {
            emit viewClicked(index.row());
            return true;
        }
    }

    return QStyledItemDelegate::editorEvent(event, model, option, index);
}

QRect OperationDelegate::getButtonRect(const QRect &cellRect, int buttonIndex) const
{
    //手动设置我们按钮所在矩阵大小
    int buttonWidth = cellRect.width() / 3 - 4;
    int x = cellRect.left() + 2 + buttonIndex * (buttonWidth + 2);
    return QRect(x, cellRect.top() + 2, buttonWidth, cellRect.height() - 4);
}
